package com.lihang.rabbit1.controller;


import com.lihang.rabbit1.common.Result;
import com.lihang.rabbit1.common.page.PageRes;
import com.lihang.rabbit1.dto.req.SysUserAddReq;
import com.lihang.rabbit1.dto.req.SysUserPageReq;
import com.lihang.rabbit1.dto.req.SysUserUpdateReq;
import com.lihang.rabbit1.dto.res.SysUserPageRes;
import com.lihang.rabbit1.entity.SysUser;
import com.lihang.rabbit1.service.ISysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

/**
 * 系统用户控制器
 */
@Validated
@Tag(name = "系统用户管理", description = "系统用户相关接口")
@RestController
@RequestMapping("/api/system/user")
public class SysUserController {

    @Autowired
    private ISysUserService userService;

    /**
     * 分页查询用户
     */
    @Operation(summary = "分页查询用户", description = "根据条件分页查询用户信息")
    @GetMapping("/page")
    public Result<PageRes<SysUserPageRes>> page(@Valid @ModelAttribute SysUserPageReq req) {
        // 调用Service执行分页查询
        PageRes<SysUserPageRes> pageRes = userService.page(req);
        return Result.success(pageRes);
    }

    /**
     * 获取用户详情
     */
    @Operation(summary = "获取用户详情", description = "根据ID获取用户详情")
    @GetMapping("/{id}")
    public Result<SysUserPageRes> getById(
            @Parameter(description = "用户ID") @PathVariable @NotNull(message = "用户ID不能为空") @Min(value = 1, message = "用户ID必须大于0") Long id) {
        // 调用Service获取用户信息 (服务层会检查ID是否存在)
        SysUserPageRes res = userService.getUserById(id);
        return Result.success(res);
    }

    /**
     * 新增用户
     */
    @Operation(summary = "新增用户", description = "新增系统用户")
    @PostMapping
    public Result<SysUserPageRes> save(@Valid @RequestBody SysUserAddReq req) {
        // 调用Service保存用户信息
        SysUserPageRes res = userService.saveUser(req);
        return Result.success(res);
    }

    /**
     * 更新用户
     */
    @Operation(summary = "更新用户", description = "更新系统用户信息")
    @PutMapping
    public Result<SysUserPageRes> update(@Valid @RequestBody SysUserUpdateReq req) {
        SysUserPageRes res = userService.updateUser(req);
        return Result.success(res);
    }

    /**
     * 删除用户
     */
    @Operation(summary = "删除用户", description = "根据ID删除系统用户")
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(
            @Parameter(description = "用户ID") @PathVariable @NotNull(message = "用户ID不能为空") @Min(value = 1, message = "用户ID必须大于0")  Long id) {
        // 调用Service删除用户
        boolean success = userService.deleteUser(id);
        return Result.success(success);
    }
}